package com.woniu.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.util.Result;
import com.woniu.utils.JwtHelper;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;

@Component
public class AutherFilter implements GlobalFilter, Ordered {

    @Resource
    private JwtHelper jwtHelper;

    //认证解析jwl
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断是否有登录状态
        String path = request.getPath().value();
        if (path.endsWith("login")){
            System.out.println("登录请求");
            return chain.filter(exchange);
        }

        String authheader = request.getHeaders().getFirst("auth-header");
        if (authheader==null||authheader.length()==0||authheader.trim().length()==0){
            return getVoidMono(response);
        }else {
            //判断是否合法
            try {

                Claims claims = jwtHelper.parseJWT(authheader);
                Object key = claims.get("key");
                // request.getHeaders().add("userId",userId.toString());
                //添加到header中，向后传递
                System.out.println(key);
                request.mutate().header("key",key.toString()).build();
            }catch (RuntimeException e){
                e.printStackTrace();
                return getVoidMono(response);

            }

        }

        return chain.filter(exchange);

    }

    //设置响应
    @Resource
    private ObjectMapper objectMapper;

    @SneakyThrows
    public Mono<Void> getVoidMono(ServerHttpResponse response){
        Result<?> result = Result.bulid().setCode(-9999).setMessage("请先登录").setFlag(false);
        //解决中文乱码问题
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        String s = objectMapper.writeValueAsString(result);
        DataBuffer dataBuffer = response.bufferFactory().wrap(s.getBytes("UTF-8"));

        return response.writeWith(Mono.just(dataBuffer));

    }


    @Override
    public int getOrder() {
        //设置比当前过滤器小
        return Ordered.LOWEST_PRECEDENCE-10;
    }
}
